package com.movie.admin.controller;

import com.movie.admin.entity.Movie;
import com.movie.admin.service.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/movies")
public class MovieController {
    @Autowired
    private MovieService movieService;

    @GetMapping
    public List<Movie> list() {
        return movieService.list();
    }

    @PostMapping
    public Movie add(@RequestBody Movie movie) {
        // 兼容前端传入average_rating和summary
        if (movie.getAverageRating() == null && movie instanceof java.util.Map) {
            Object avg = ((java.util.Map)movie).get("average_rating");
            if (avg != null) movie.setAverageRating(new java.math.BigDecimal(avg.toString()));
        }
        if (movie.getSummary() == null && movie instanceof java.util.Map) {
            Object sum = ((java.util.Map)movie).get("summary");
            if (sum != null) movie.setSummary(sum.toString());
        }
        movieService.save(movie);
        return movie;
    }

    @PutMapping("/{id}")
    public Movie update(@PathVariable Integer id, @RequestBody Movie movie) {
        movie.setId(id);
        // 兼容前端传入average_rating和summary
        if (movie.getAverageRating() == null && movie instanceof java.util.Map) {
            Object avg = ((java.util.Map)movie).get("average_rating");
            if (avg != null) movie.setAverageRating(new java.math.BigDecimal(avg.toString()));
        }
        if (movie.getSummary() == null && movie instanceof java.util.Map) {
            Object sum = ((java.util.Map)movie).get("summary");
            if (sum != null) movie.setSummary(sum.toString());
        }
        movieService.updateById(movie);
        return movie;
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Integer id) {
        movieService.removeById(id);
    }

    @GetMapping("/test")
    public String testDb() {
        int count = movieService.list().size();
        return "数据库中电影数量: " + count;
    }

    @GetMapping("/{id}")
    public Movie getById(@PathVariable Integer id) {
        return movieService.getById(id);
    }

    @GetMapping("/search")
    public List<Movie> search(@RequestParam String keyword) {
        System.out.println("收到搜索请求，keyword=" + keyword);
        List<Movie> result = movieService.lambdaQuery()
            .like(Movie::getTitle, keyword)
            .or().like(Movie::getDirector, keyword)
            .or().like(Movie::getCast, keyword)
            .or().like(Movie::getGenres, keyword)
            .list();
        System.out.println("搜索结果数量=" + result.size());
        return result;
    }

    @GetMapping("/top-rated")
    public List<Object> getTopRatedMovies() {
        List<Movie> movies = movieService.findTop10ByOrderByAverageRatingDesc();
        // 适配小程序端格式
        List<Object> result = new java.util.ArrayList<>();
        for (Movie movie : movies) {
            java.util.Map<String, Object> map = new java.util.HashMap<>();
            map.put("id", movie.getId());
            map.put("title", movie.getTitle());
            map.put("original_title", movie.getOriginalTitle());
            java.util.Map<String, Object> images = new java.util.HashMap<>();
            images.put("large", movie.getImageUrl());
            map.put("images", images);
            java.util.Map<String, Object> rating = new java.util.HashMap<>();
            rating.put("average", movie.getAverageRating());
            map.put("rating", rating);
            map.put("directors", splitToNameList(movie.getDirector()));
            map.put("casts", splitToNameList(movie.getCast()));
            map.put("genres", splitToList(movie.getGenres()));
            map.put("year", movie.getReleaseDate() != null && movie.getReleaseDate().length() >= 4 ? movie.getReleaseDate().substring(0, 4) : "");
            map.put("summary", movie.getSummary());
            result.add(map);
        }
        return result;
    }

    // 工具方法：逗号分割转List<Map<String, String>>
    private java.util.List<java.util.Map<String, String>> splitToNameList(String str) {
        java.util.List<java.util.Map<String, String>> list = new java.util.ArrayList<>();
        if (str != null && !str.trim().isEmpty()) {
            for (String s : str.split("，|,")) {
                java.util.Map<String, String> m = new java.util.HashMap<>();
                m.put("name", s.trim());
                list.add(m);
            }
        }
        return list;
    }
    // 工具方法：逗号分割转List<String>
    private java.util.List<String> splitToList(String str) {
        java.util.List<String> list = new java.util.ArrayList<>();
        if (str != null && !str.trim().isEmpty()) {
            for (String s : str.split("，|,")) {
                list.add(s.trim());
            }
        }
        return list;
    }
} 